﻿using System;
using System.Web;
using Icst.Leaflike.Web;
using Icst.Leaflike.Logging;

namespace Icst.Leaflike.Web
{
    public class ThrotlingModule : IHttpModule
    {
        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(this.Application_BeginRequest);
            //context.LogRequest += new EventHandler(OnLogRequest);
        }
        public void Application_BeginRequest(Object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;
            HttpContext context = application.Context;

            int userCount = context.Application.UserCount();
            if (userCount > AppConfig.forbiddenthrehold)
            {
                application.CompleteRequest();
                context.Response.StatusCode = 503;
                context.Response.StatusDescription = "Service Unavailable";
                context.Response.Write(Alert("目前在线人数过多，请稍候再访问。"));
                Logger.Warning("FORBIDDEN USER ACOUNT EXCEED:" + userCount + " > " + AppConfig.forbiddenthrehold);
            }
            else if (userCount > AppConfig.onlineuserthrehold)
            {
                context.Response.Clear();

                context.Response.Write("<br/>");
                context.Response.Write("<br/>");
                context.Response.Write(Alert("目前在线人数过多，本网站相应时间会变慢，建议您换个时间再次访问。"));
                context.Response.Write("<br/>");
                context.Response.Write("<br/>");

                Logger.Warning("ONLINE USER ACOUNT EXCEED:" + userCount + " > " + AppConfig.onlineuserthrehold);
            }
        }
        private string Alert(string text)
        {
            return string.Format("<span style=\"color:red\"><strong>{0}</strong></span>",text);
        }
        //public void OnLogRequest(Object source, EventArgs e)
        //{
        //}
    }
}
